import { connect } from 'dva';
import * as THREE from 'three'
import { useEffect, useRef } from 'react';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { Water } from 'three/examples/jsm/objects/Water2.js'
import * as TWEEN from 'three/examples/jsm/libs/tween.module.js'
import styles from './testPc.less'

 const TestPCPage = (props) => {
   const sceneRef = useRef(null)
   const cameraRef = useRef(null)
   const rendererRef = useRef(null)
   const guiRef = useRef(null)
   const width = window.innerWidth; //宽度
   const height = window.innerHeight; //高度
   useEffect(()=>{
    init()
   }, [])
   const init = () => {
      // 0.添加GUI
      const eventObj = {
        Fullscreen: function(){
         document.body.requestFullscreen()
        },
        Exitscreen: () => {
          document.exitFullscreen()
        }
      }
      guiRef.current = new GUI()
      guiRef.current.add(eventObj, "Fullscreen").name('全屏')
      guiRef.current.add(eventObj, "Exitscreen").name('退出全屏')
      let colorParams = {
        cubeColor: '#00ff00'
      }
      guiRef.current.addColor(colorParams, "cubeColor").name('颜色辅助器')

      // 1.创建3D场景对象Scene
      sceneRef.current = new THREE.Scene();

      // 4.加载几何体/模型
      setGeometry()

      // 2. 定义虚拟相机部分
      setCamera()

      // 5. 坐标辅助器
      const axesHelper = new THREE.AxesHelper(500)
      sceneRef.current.add(axesHelper)

      // 3.渲染器
      setRenderer()

      window.addEventListener("resize",()=>{
        rendererRef.current.setSize(window.innerWidth,window.innerHeight);
        cameraRef.current.aspect = window.innerWidth/window.innerHeight;
        cameraRef.current.updateProjectionMatrix()
      })

   }

   // 创建相机
   const setCamera = () => {
      // width和height用来设置Three.js输出的Canvas画布尺寸(像素px)
      cameraRef.current = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
      // 实例化一个透视投影相机对象
      // 根据需要设置相机位置具体值
      cameraRef.current.position.set(80, 80, 0);
      cameraRef.current.lookAt(0,0,0);//指向mesh对应的位置
   }
   // 创建几何体
   const setGeometry = () => {
      //  example 1：加载模型
      getModel()   
   }
   // 创建渲染器
   const setRenderer = () => {
      // 创建渲染器对象
      rendererRef.current = new THREE.WebGLRenderer({
        antialias: true, //抗锯齿
        logarithmicDepthBuffer: true, //对数深度缓冲区，设置之后防止物体多了刷新不过来，视觉卡
      });
      // 输出的环境编码
      rendererRef.current.outputEncoding = THREE.sRGBEncoding;
      rendererRef.current.shadowMap.enabled = true; //开启阴影
      rendererRef.current.setSize(width, height); //设置three.js渲染区域的尺寸(像素px)
      rendererRef.current.render(sceneRef.current, cameraRef.current); //执行渲染操作
      document.getElementById('webgl').appendChild(rendererRef.current.domElement);
      // 6. 轨道控制器
      const controls = new OrbitControls(cameraRef.current, rendererRef.current.domElement)

      function animate(){
        requestAnimationFrame(animate)
        controls.update() 
        rendererRef.current.render(sceneRef.current, cameraRef.current)
      }
      animate()
   }
   // 导入模型
   const getModel = () => {
      // 使用背景纹理：创造一个巨大的球
     const skyGeometry = new THREE.SphereGeometry(1000,60,60);
     const skyMaterial = new THREE.MeshBasicMaterial({
         map: new THREE.TextureLoader().load(require('../assets/img2/bg-login.png'))
     })
     const sky = new THREE.Mesh(skyGeometry, skyMaterial)
     sceneRef.current.add(sky)
     skyGeometry.scale(1,1,-1);

     // 添加灯光
     // 1.环境光
     const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
     sceneRef.current.add(ambientLight)
     // 2.平行光1
     const directionalLight = new THREE.DirectionalLight(0xfbff00, 0.5);
     directionalLight.position.set(0,0,1);
     directionalLight.castShadow = true;
     directionalLight.shadow.radius = 20;
     directionalLight.shadow.mapSize.set(2048, 2048)
     const directionalLight2 = new THREE.DirectionalLight(0xfbff00, 0.5);
     directionalLight2.position.set(0,0,-1);
     directionalLight2.castShadow = true;
     directionalLight2.shadow.radius = 20;
     directionalLight2.shadow.mapSize.set(2048, 2048)
     sceneRef.current.add(directionalLight2)

      const loader = new THREE.TextureLoader();
      const bgTexture = loader.load(require('../assets/img2/logo.png'));
      bgTexture.mapping = THREE.EquirectangularRefractionMapping; // 折射效果，折射到物体上
      sceneRef.current.background = bgTexture;
      sceneRef.current.environment = bgTexture;

      // sceneRef.current.background = new THREE.Color(0x999999)
      const gltfLoader = new GLTFLoader();
      gltfLoader.load(require('.././assets/model/test.glb'), (glb) => {
          console.log(glb)
          sceneRef.current.add(glb.scene)
          // 给一个物体设置Phong材质,设置水晶
          const translateMaterial = new THREE.MeshPhongMaterial({
            color: 0xb6f7b6,
            envMap: bgTexture,
            refractionRatio: 0.7,
            reflectivity: 0.99,
            opacity: 0.8,
          })
          const model = glb.scene;
          const customMaterial = new THREE.MeshBasicMaterial({
            color: 0x00ff00,
          }) 
          model.traverse((child)=>{
            if(child.isMesh){
                child.castShadow = true;
                if(child.name == 'dimian'){
                    child.receiveShadow = true;  
                }
                if(child.name.includes("柱体")){
                    child.material = translateMaterial;
                }
                if(child.name.includes("fox") || child.name.includes("leaves")){
                    child.material = translateMaterial;
                }
                // if(child.name == 'treetrunk'){
                //     console.log(child)
                //     child.material = customMaterial;
                // }
            }
        }) 
        
        const childTreeModel = glb.scene.getObjectByName("treetrunk");
        const childTreeGeometry = childTreeModel.geometry;
        childTreeModel.material = customMaterial;
        console.log(childTreeModel, '---customeModel')
        // 功能点1：某个物体随着鼠标移动可以来回动--treetrunk
        const mouse = new THREE.Vector2();
        document.getElementById('webgl').addEventListener('mousemove',(event)=>{
            //鼠标点击坐标
            const px = event.offsetX;
            const py = event.offsetY;
            //转化坐标
            mouse.x = (px / width)*2-1;
            mouse.y = -((py / height)*2-1);
            // 传入球的位置
            // const tween = new TWEEN.Tween(childTreeModel.position)
            // // 去到哪个位置
            // tween.to({ x: 4, y: 3}, 1500)
            // 使用gsap库旋转物体
            // let timeline = gsap.timeline();
            // timeline.to(childTreeModel.rotation,{
            //   duration: 0.5,
            //   x: y,
            //   y: x,
            //   duration: 1,
            // })
        })
      })
   }


  return (
    <div>
        <div className={styles.pages}>
            <h1 className={styles.text_wrap}>可视化官网1</h1>
            <div id="webgl"></div>
        </div>
        <div className={styles.pages}>
            <h1 className={styles.text_wrap}>可视化官网2</h1>
            <div id="webgl2"></div>
        </div>
        <div className={styles.pages}>
            <h1 className={styles.text_wrap}>可视化官网3</h1>
            <div id="webgl3"></div>
        </div>
    </div>
  );
}
export default connect(({common})=>({
  userInfo: common.userInfo,
}))(TestPCPage)